﻿using System;
using System.Xml.Linq;
using Orchard;
using Orchard.Caching;
using Orchard.Services;
using PlanetTelex.RssViewer.Models;

namespace PlanetTelex.RssViewer.Services {
    public interface IRssViewerService : IDependency {
        XElement GetFeed(RssViewerPart rssPart);
    }

    public class RssViewerService : IRssViewerService {
        private readonly IClock _clock;
        private readonly ICacheManager _cacheManager;
        private const string RssViewer = "PlanetTelex.RSSCache.";

        public RssViewerService(IClock clock, ICacheManager cacheManager) {
            _clock = clock;
            _cacheManager = cacheManager;
        }

        public XElement GetFeed(RssViewerPart rssPart) {
            var feed = _cacheManager.Get(RssViewer + rssPart.FeedUrl,
                s => {
                    s.Monitor(_clock.When(TimeSpan.FromMinutes(rssPart.CacheDuration)));
                    var f = XElement.Load(rssPart.FeedUrl);
                    return f;
                }
                );
            return feed;
        }
    }
}